<?php


use Swoole\Coroutine as co;

$ws = new swoole_websocket_server('172.17.0.2',9502);
co::set(['max_coroutine'=>4096]);

$ws->set(['reactor_num'=>4,'worker_num'=>4]);
$ws->on('WorkerStart', function ($ws, $worker_id) { 
   	echo 1;
 	$chan = new co\channel(1);
	go(function() use($chan){
		 var_dump(time());

		for ($i=0; $i <2 ; $i++) { 
			co::sleep(3.0);
			$chan->push(['rand' => rand(1000, 9999), 'index' => $i]);
			echo "$i\n";
			# code...
		}
		
 	});

 //    go(function () use ($chan) {
	//     while(1) {
	//         $data = $chan->pop();
	//         print_r($data);
	//     }
	// });
	//swoole_event::wait();


	//让出权  
   
	// $cid = go(function () {
 //    echo "co 1 start\n";
 //    co::yield();
 //    echo "co 1 end\n";
	// });

	// go(function () use ($cid) {
	//     echo "co 2 start\n";
	//     co::sleep(0.5);
	//     co::resume($cid);
	//     echo "co 2 end\n";
	// });
	go(function () use ($chan) {
        var_dump(time());

        $mysql = new Swoole\Coroutine\MySQL();
        $mysql->connect([
            'host' => '127.0.0.1',
            'user' => 'root',
            'password' => 'root',
            'database' => 'test',
        ]);
        $result = $mysql->query('select sleep(3)');

        $chan->push($result);
    });
   	
	$results = [];
    for ($i = 0; $i < 3; $i++) {
        $results[] = $chan->pop();
    }
    print_r($results);


    


    
   



});


$ws->on('connect',function($ws,$id){
	echo 2;
	//echo $id;
	//状态 
	print_r($ws->stats());
});

//监听WebSocket连接打开事件 (这里会得到很多信息)
$ws->on('open',function($ws,$request){
	echo 3;
	//print_r($request);
	//用户序号  fd

});

$ws->on("message",function($ws,$frame){

	echo 4;	
	echo co::getCid();
	//print_r($frame);
	
});

$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});



$ws->start();